Telegram Group & Telegram Channel
Что выведет этот код? (C++23)


import std;

constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
}

int main() {
auto checker = make_checker();

std::vector numbers{1, 3, 5, 9, 10, 14, 15};

auto filtered = numbers | std::views::filter([&](int x) {
if (std::is_constant_evaluated()) {
std::print("constexpr\n");
}
return checker(x);
});

std::print("Filtered numbers: ");
for (int x : filtered) {
std::print("{} ", x);
}

std::println("");
}


🧠 Подсказка:
consteval делает checker доступным только в compile-time, но мы вызываем его в runtime через лямбду — что произойдёт?

std::is_constant_evaluated() — интересный механизм проверки, вызывается ли код во время компиляции.

Как отреагирует компилятор на попытку вызвать consteval функцию в runtime?


📌 Ответ
Этот код на C++23 не скомпилируется, и что именно здесь происходит.

🔍 Напоминаем ключевой фрагмент кода:

```cpp
constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
} ```

- Здесь создаётся лямбда-функция, помеченная как consteval.

- Ключевое слово consteval означает: функция обязана быть вызвана во время компиляции.

🧨 Где ошибка?


auto filtered = numbers | std::views::filter([&](int x) {
return checker(x); // ← ошибка тут
});


checker — это consteval-лямбда.

Но ты вызываешь её внутри лямбды, которая будет работать во время выполнения программы — т.е. в runtime.

Это нарушение правила consteval → нельзя вызывать такие функции в runtime-коде.

Что скажет компилятор?
Компилятор выдаст ошибку компиляции, такую или похожую:

error: call to consteval function '<lambda>(int)' is not a constant expression



📘 Объяснение
consteval ≠ constexpr

constexpr — это могут быть вызваны в runtime, если нужно.

consteval — это всегда и только compile-time.

Когда ты вызываешь checker(x) в main(), ты нарушаешь это правило.

Как можно исправить?
Если ты заменишь consteval на constexpr, код скомпилируется и выполнится:


constexpr auto make_checker() {
return [](int x) constexpr {
return x % 3 == 0 || x % 5 == 0;
};
}

И тогда результат будет:

Filtered numbers: 3 5 9 10 15

Потому что:
- 3 делится на 3
- 5 делится на 5
- 9 делится на 3
- 10 делится на 5
- 15 делится на 3 и 5



tg-me.com/cpluspluc/1026
Create:
Last Update:

Что выведет этот код? (C++23)


import std;

constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
}

int main() {
auto checker = make_checker();

std::vector numbers{1, 3, 5, 9, 10, 14, 15};

auto filtered = numbers | std::views::filter([&](int x) {
if (std::is_constant_evaluated()) {
std::print("constexpr\n");
}
return checker(x);
});

std::print("Filtered numbers: ");
for (int x : filtered) {
std::print("{} ", x);
}

std::println("");
}


🧠 Подсказка:
consteval делает checker доступным только в compile-time, но мы вызываем его в runtime через лямбду — что произойдёт?

std::is_constant_evaluated() — интересный механизм проверки, вызывается ли код во время компиляции.

Как отреагирует компилятор на попытку вызвать consteval функцию в runtime?


📌 Ответ
Этот код на C++23 не скомпилируется, и что именно здесь происходит.

🔍 Напоминаем ключевой фрагмент кода:

```cpp
constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
} ```

- Здесь создаётся лямбда-функция, помеченная как consteval.

- Ключевое слово consteval означает: функция обязана быть вызвана во время компиляции.

🧨 Где ошибка?


auto filtered = numbers | std::views::filter([&](int x) {
return checker(x); // ← ошибка тут
});


checker — это consteval-лямбда.

Но ты вызываешь её внутри лямбды, которая будет работать во время выполнения программы — т.е. в runtime.

Это нарушение правила consteval → нельзя вызывать такие функции в runtime-коде.

Что скажет компилятор?
Компилятор выдаст ошибку компиляции, такую или похожую:

error: call to consteval function '<lambda>(int)' is not a constant expression



📘 Объяснение
consteval ≠ constexpr

constexpr — это могут быть вызваны в runtime, если нужно.

consteval — это всегда и только compile-time.

Когда ты вызываешь checker(x) в main(), ты нарушаешь это правило.

Как можно исправить?
Если ты заменишь consteval на constexpr, код скомпилируется и выполнится:


constexpr auto make_checker() {
return [](int x) constexpr {
return x % 3 == 0 || x % 5 == 0;
};
}

И тогда результат будет:

Filtered numbers: 3 5 9 10 15

Потому что:
- 3 делится на 3
- 5 делится на 5
- 9 делится на 3
- 10 делится на 5
- 15 делится на 3 и 5

BY C++ Academy


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpluspluc/1026

View MORE
Open in Telegram


C Academy Telegram | DID YOU KNOW?

Date: |

Export WhatsApp stickers to Telegram on iPhone

You can’t. What you can do, though, is use WhatsApp’s and Telegram’s web platforms to transfer stickers. It’s easy, but might take a while.Open WhatsApp in your browser, find a sticker you like in a chat, and right-click on it to save it as an image. The file won’t be a picture, though—it’s a webpage and will have a .webp extension. Don’t be scared, this is the way. Repeat this step to save as many stickers as you want.Then, open Telegram in your browser and go into your Saved messages chat. Just as you’d share a file with a friend, click the Share file button on the bottom left of the chat window (it looks like a dog-eared paper), and select the .webp files you downloaded. Click Open and you’ll see your stickers in your Saved messages chat. This is now your sticker depository. To use them, forward them as you would a message from one chat to the other: by clicking or long-pressing on the sticker, and then choosing Forward.

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

C Academy from hk


Telegram C++ Academy
FROM USA